from django.conf import settings
from django.contrib.auth import login, authenticate
from django.contrib.auth.models import User
from django.core.serializers import json
from django.core.urlresolvers import reverse
from django.http import HttpResponseRedirect
from django.views.generic.simple import direct_to_template
from django.utils.translation import ugettext as _

from simpleopenid.auth.backends import COMPLETE
from simpleopenid.models import Provider

from simpleopenid.views.generic import openid_login as generic_openid_login


__all__ = ['openid_login', 'openid_complete', 'openid_form_js',]

json_serializer = json.Serializer()


def custom_openid_complete(request):
    
    result = authenticate(step=COMPLETE, data=(request.GET,
        request.build_absolute_uri(),), session=request.session)
    
    if isinstance(result, User):
        
        login(request, result)
        # Django 1.4 no longer has 'message_set'
        # request.user.message_set.create(message=_('You are logged in.'))
        from django.contrib import messages
        messages.success(request, _('You are logged in.'))
        return HttpResponseRedirect(request.user.get_absolute_url())
    else:
        return HttpResponseRedirect(reverse('index'))
